package com.example.demo.Controller;

import com.example.demo.Entity.IllegalAction;
import com.example.demo.Entity.OrderList;
import com.example.demo.Entity.ShopUser;
import com.example.demo.Entity.UserMessage;
import com.example.demo.Service.*;
import com.example.demo.Vo.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;

@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private BookService bookService;
    @Autowired
    private UserMessageService userMessageService;
    @Autowired
    private UserActionService userActionService;
    //订单:创建订单 查看历史订单 修改订单 取消订单
    @PostMapping("/api/create_order")
    public Response createOrder(HttpServletRequest request, @RequestBody Map<String, String> reMap){
        OrderList order = new OrderList();
        Response response = null;
        Map<String, OrderList> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String UserId = (String)request.getSession().getAttribute("uid");
        ShopUser user = userService.selectUserByUserID(UserId);

        String UserName = user.getUsername();

        Date OrderDate = new Date();
        Date ShipDate;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(OrderDate); //需要将date数据转移到Calender对象中操作
        calendar.add(Calendar.DATE, 2);//把日期往后增加n天.正数往后推,负数往前移动
        ShipDate = calendar.getTime();

        String Remark = reMap.get("remark");
        String Address = reMap.get("address");
        String ISBN = reMap.get("isbn");
        String temNumber = reMap.get("number");
        try{
            order.setOrderDate(OrderDate);
            order.setCustomerId(UserId);
            order.setIsShipped(false);
            order.setShipDate(ShipDate);
            order.setCustomerAddress(Address);
            order.setISBN(ISBN);
            order.setCustomerName(UserName);
            order.setIsPayed(false);
            order.setConfirmed(false);
            order.setRemark(Remark);
            try{
                int Number = Integer.parseInt(temNumber);
                if(Number <= 0 ){
                    response = Response.createByErrorMessage("购买数量不可小于0");
                    return response;
                }
                if(Number > bookService.selectBookByISBN(ISBN).getTotalCount()) {
                    response = Response.createByErrorMessage("购买数量超过库存");
                    return response;
                }
                order.setNumber(Number);
                order.setPrice(bookService.selectBookByISBN(ISBN).getPrice()*Number);

                if(orderService.createOrder(order) == false){
                    response = Response.createByErrorMessage("请填写您的收货地址");
                    return response;
                }
                else{
                    map.put("order",orderService.selectNewestOrder());
                    bookService.editBookTotalCount(ISBN, String.valueOf(bookService.selectBookByISBN(ISBN).getTotalCount() - Number));
                    if(orderService.noPayOrder(user.getUserID()) >= 5){
                        response = Response.createByErrorMessage("您未支付的订单过多，请先支付以前的订单");
                        IllegalAction illegalAction = new IllegalAction();
                        illegalAction.setUserID(UserId);
                        illegalAction.setOrderID(orderService.selectNewestOrder().getOrderId());
                        illegalAction.setActionDate(new Date());
                        illegalAction.setDetail("未支付订单过多");
                        userActionService.addNewAction(illegalAction);
                        orderService.cancelOrder(orderService.selectNewestOrder().getOrderId());
                        bookService.editBookTotalCount(ISBN, String.valueOf(bookService.selectBookByISBN(ISBN).getTotalCount() + Number));
                        return response;
                    }
                    response = Response.createBySuccess("创建订单成功，请尽快支付",map);
                }
            } catch(Exception e){
                e.printStackTrace();
                response = Response.createByErrorMessage("购买数量形式错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/check_my_order")
    public Response checkMyOrder(HttpServletRequest request){
        Response response = null;
        Map<String, ArrayList<OrderList>> map = new HashMap<>();
        try{
            String userid = (String) request.getSession().getAttribute("uid");
            ArrayList<OrderList> orderLists = orderService.selectOrderByUid(userid);
            if(orderLists.isEmpty()){
                response = Response.createByErrorMessage("这里还没有订单呢~");
                return response;
            }
            ArrayList<OrderList> payedOrder = new ArrayList<>();
            ArrayList<OrderList> notPayedOrder = new ArrayList<>();
            for (OrderList order : orderLists) {
                if(order.isIsPayed()) {
                    payedOrder.add(order);
                }
                else {
                    notPayedOrder.add(order);
                }
            }
            map.put("orderList", orderLists);
            map.put("payedOrderList", payedOrder);
            map.put("notPayedOrderList", notPayedOrder);
            response = Response.createBySuccess("成功查询订单",map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/edit_order")
    public Response editOrder(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        Map<String, OrderList> map = new HashMap<>();
        //只能修改:备注 购买数量
        //String Remark = reMap.get("remark");
        //String Number = reMap.get("number");
        String address = reMap.get("address");
        String temorderId = reMap.get("orderId");
        long OrderId = Long.parseLong(temorderId);
        OrderList order = orderService.selectOrderByOid(OrderId);
        int originalNumber = order.getNumber();
        if(order.isConfirmed()){
            response = Response.createByErrorMessage("订单已经确认，不可取消或更改");
            return response;
        }
        try{
            orderService.editOrderAddress(OrderId, address);
            OrderList neworder = orderService.selectOrderByOid(OrderId);
            map.put("editOrder",neworder);
            response = Response.createBySuccess("修改订单成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/cancel_order")
    public Response cancelOrder(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String temorderId = reMap.get("orderId");
        long OrderId = Long.parseLong(temorderId);
        OrderList order = orderService.selectOrderByOid(OrderId);
        Map<String, Date> map = new HashMap<>();
        Date date = new Date();
        map.put("cancelDate", date);
        if(order.isConfirmed()){
            response = Response.createByErrorMessage("订单已经确认，不可取消或更改");
            return response;
        }
        try{
            bookService.editBookTotalCount(order.getISBN(),String.valueOf(bookService.selectBookByISBN(order.getISBN()).getTotalCount()+order.getNumber()));
            orderService.cancelOrder(OrderId);
            response = Response.createBySuccess("取消订单",map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/confirm_order")
    public Response confirmOrder(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String temorderId = reMap.get("orderId");
        long OrderId = Long.parseLong(temorderId);
        Map<String, Date> map = new HashMap<>();
        Date date = new Date();
        map.put("confirmlDate", date);
        try{
            orderService.confirmOrder(OrderId);
            response = Response.createBySuccess("已成功确认订单", map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/pay_order")
    public Response payOrder(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        String temorderId = reMap.get("orderId");
        long OrderId = Long.parseLong(temorderId);
        Map<String, Date> map = new HashMap<>();
        Date date = new Date();
        map.put("payDate", date);
        try{
            OrderList order = orderService.selectOrderByOid(OrderId);
           if(order.isIsPayed()){
               response = Response.createByErrorMessage("已经付过钱了");
               return  response;
           }
            orderService.payOrder(OrderId);
            response = Response.createBySuccess("支付成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @PostMapping("/api/create_message")
    public Response createMessage(HttpServletRequest request, @RequestBody Map<String, String> reMap) {
        Response response = null;
        Map<String, UserMessage> map = new HashMap<>();
        String userId = (String) request.getSession().getAttribute("uid");
        String content = reMap.get("messageContent");
        String messageType = reMap.get("messageType");
        System.out.println(content+" "+messageType);
        try {
            UserMessage userMessage = new UserMessage();
            userMessage.setMessageType(messageType);
            userMessage.setMessageContent(content);
            userMessage.setUserId(userId);
            userMessageService.createNewMessage(userMessage);
            UserMessage returnMessage = new UserMessage();
            returnMessage = userMessageService.getLast(userId);
            map.put("message",returnMessage);
            response = Response.createBySuccess("createMessage", map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }

    @GetMapping("/api/get_message")
    public Response getMessage(HttpServletRequest request ) {
        Response response = null;
        String userId = (String) request.getSession().getAttribute("uid");
        Map<String, ArrayList<UserMessage>> map = new HashMap<>();
        try{
            ArrayList<UserMessage> messageList = userMessageService.getMessage(userId);
            map.put("messageList", messageList);
            response = Response.createBySuccess("成功查询消息列表", map);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.createByError();
        }
        return response;
    }
}
